package smashedapples.microsoft.sqlserver
{
	import mx.collections.ArrayCollection;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	import smashedapples.core.NonVisualComponent;
	import smashedapples.microsoft.events.SqlServerEvent;
	import smashedapples.microsoft.sqlserver.commands.SelectCommand;
	import smashedapples.microsoft.sqlserver.responses.SelectResponse;
	import smashedapples.utils.ValueObjectUtils;
	

	[Event(name="onSelectResult",type="smashedapples.microsoft.events.SqlServerEvent")]
	[Event(name="onSelectFault",type="smashedapples.microsoft.events.SqlServerEvent")]

	[DefaultProperty("command")]
	public class DataQuery extends NonVisualComponent
	{
		public function DataQuery()
		{
			super();
		}

		public var server : SqlServer;
		
		public var itemType : Class;
		
		public var command : SelectCommand;
		
		[Bindable]
		public var result : ArrayCollection;
	
		public function send(args:Object=null):AsyncToken
		{
			if( args != null)
				this.command.parameters = args;
			
			return this.server.select( this.command, this.resultHandler, this.faultHandler );
		}
		
	
		private function faultHandler(event:FaultEvent):void
		{
			this.dispatchEvent( new SqlServerEvent( SqlServerEvent.ON_SELECT_FAULT, {response: event.fault} ));
			
			Debug.push( this, event.fault );	
		}
		
		private function resultHandler(event:ResultEvent):void
		{
			if( !event.result is SelectResponse)
				return;
			
			var response : SelectResponse = event.result as SelectResponse;

			if( this.itemType != null)
			{	
				var array : Array = ValueObjectUtils.typeArray(  response.data as Array, itemType );
				this.result = new ArrayCollection(array);			
			}
			else
			{
				this.result = new ArrayCollection(response.data as Array);
			}
	
			this.dispatchEvent( new SqlServerEvent( SqlServerEvent.ON_SELECT_RESULT, {response: response} ));
			
			if(response.debug)
				Debug.push( this, response.info );
		}
		
		
		
		public function saveHandler(event:ResultEvent):void
		{
			trace("save handler");
		}
		
		public function clear():void
		{
			this.result = new ArrayCollection();
		}
		
		
		
		
		
		
		

	}
}